<?php

namespace App\Controller\Home;

use App\Controller\Example\CartGoodsExample;
use App\Controller\Example\UserExample;
use App\Models\CartGoodsModel;
use App\Models\ConfigModel;
use App\Models\UsersModel;
use Config\Config;
use Core\Common\Common;
use Core\Enums\DigitEnum;
use Core\Enums\ErrorEnum;
use Core\Enums\FundsEnum;
use Core\Result\Result;
use Core\Utils\Utils;

class Sett
{
    /**
     * 购物增加自己业绩
     * */
    public static function addUserAch($conn,$UserExample,$orderMoney,$CartExample){
        $cartGoodsExample = new CartGoodsExample();
        $cartGoodsExample->cid = $CartExample->id;
        $cartGoodsExample->uid = $CartExample->uid;
        $orderNumber = CartGoodsModel::getOrderCartGoodsOneNumberInsideCid($conn, $cartGoodsExample);
        $oneMoney = $orderMoney / $orderNumber;
        if(UsersModel::editUserAchAddInside($conn,$orderMoney,$oneMoney,$orderNumber,$UserExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::PAYMENTFAILED."addUserAch");
        }
        self::settlement($conn,$UserExample,$orderMoney,$orderNumber,$CartExample->serial);
        self::promotion($conn,$UserExample);
        //self::activationEducation($conn,$UserExample);
    }
    /**
     * 结算
     * */
    public static function settlement($conn,$UserExample,$orderMoney,$orderNumber,$serial){
        $userSuperiorAllPid = UsersModel::getUserSuperiorAllPid($conn, $UserExample->pid);
        $int = DigitEnum::ONE;
        $MaxLevel = $LastAwardVal = $Level = DigitEnum::ZERO;
        foreach ($userSuperiorAllPid as $value){
            $User = Common::assemble(new UserExample(), $value);
            if($int == DigitEnum::ONE && $orderMoney > DigitEnum::ZERO){
                $User1 = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
                //if($User1->level > DigitEnum::ZERO && $User1->ach > DigitEnum::ZERO){
                    self::salesCommission($conn,$User1,$orderMoney,$orderNumber,$serial);
                //}
                $User2 = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
                if($User2->service >= DigitEnum::THREE && $User2->one_ach >= DigitEnum::ONE && $User2->push_reward == DigitEnum::ZERO){
                    self::quotaCommission($conn,$User2,$serial);
                }
            }
            if($User->level > $MaxLevel){
                $levelAward = self::getLevelAward($conn, $User->level);
                $award = $levelAward - $LastAwardVal;
                if($levelAward > DigitEnum::ZERO)$LastAwardVal = $levelAward;
                $award = $award > DigitEnum::ONE ? $award:$orderMoney * $award;
                $User3 = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
                self::managementFees($conn,$User3,$award,$serial);
                $MaxLevel = $User->level;
            }
            if($Level == DigitEnum::ZERO && $MaxLevel == DigitEnum::FOUR && $User->level == $MaxLevel){
                $User4 = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
                self::advertisingCost($conn,$User4,$orderMoney,$serial);
                $Level = DigitEnum::ONE;
            }
            self::updatePerformance($conn,$User,$orderMoney);
            $int++;
        }
        $userSuperiorAllSid = UsersModel::getUserEducation($conn, DigitEnum::SIX);
        self::educationAndrainingExpenses($conn,$userSuperiorAllSid,$orderMoney,$orderNumber,$serial);
    }
    /**
     * 销售提成
     * */
    public static function salesCommission($conn, $UserExample, $orderMoney,$orderNumber,$orderNo){
        $award = DigitEnum::ZERO;
        $service = $orderNumber;
        while ($orderNumber > DigitEnum::ZERO){
            switch ($UserExample->service){
                case DigitEnum::ZERO : $awardVal = self::getAwardVal($conn,Config::ONESALE_REWARDS);break;
                case DigitEnum::ONE : $awardVal = self::getAwardVal($conn,Config::TWOSALE_REWARDS);break;
                default : $awardVal = self::getAwardVal($conn,Config::THREESALE_REWARDS);break;
            }
            $award += $awardVal > DigitEnum::ONE ? $awardVal:$orderMoney * $awardVal;
            $UserExample->service++;
            $orderNumber--;
        }
        if($award > DigitEnum::MINIMUM){
            $FundsType = FundsEnum::DIRECTPROMOTIONREWARD;
            if(UsersModel::editUserPidSettlementInside($conn,$award,$service,$UserExample) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $UserExample->id, $orderNo, $FundsType, $award, $UserExample->money + $award, $FundsType) != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED."salesCommission");
            }
        }
    }
    /**
     * 定额提成
     * */
    public static function quotaCommission($conn, $UserExample, $orderNo){
        $awardVal = self::getAwardVal($conn,Config::PRINCIPAL_REWARDS);
        $award = $awardVal * $UserExample->one_ach;
        if($award > DigitEnum::MINIMUM){
            $FundsType = FundsEnum::INTERPROMOTIONREWARD;
            if(UsersModel::editUserSettlementInside($conn,$award,$UserExample) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $UserExample->id, $orderNo, $FundsType, $award, $UserExample->money + $award, $FundsType) != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED."quotaCommission");
            }
        }
    }
    /**
     * 管理费
     * */
    public static function managementFees($conn,$UserExample,$award,$orderNo){
        if($award > DigitEnum::MINIMUM){
            $FundsType = FundsEnum::SERVICEPROVIDERREWARD;
            if(UsersModel::editUserAgentSettlementInside($conn,$award,$UserExample) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $UserExample->id, $orderNo, $FundsType, $award, $UserExample->money + $award, $FundsType) != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED."managementFees");
            }
        }
    }
    /**
     * 广告费
     * */
    public static function advertisingCost($conn,$UserExample,$orderMoney,$orderNo){
        $awardVal = self::getAwardVal($conn,Config::AD_REWARDS);
        $award = $awardVal > DigitEnum::ONE ? $awardVal:$orderMoney * $awardVal;
        if($award > DigitEnum::MINIMUM){
            $FundsType = FundsEnum::SHAREHOLDING;
            if(UsersModel::editUserLevelAgentSettlementInside($conn,$award,$UserExample) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $UserExample->id, $orderNo, $FundsType, $award, $UserExample->money + $award, $FundsType) != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED."advertisingCost");
            }
        }
    }
    /**
     * 教培费
     * */
    public static function educationAndrainingExpenses($conn,$userSuperiorAllSid,$orderMoney,$orderNumber,$orderNo){
        $awardVal = self::getAwardVal($conn, Config::DRILL_REWARDS);
        $award = $awardVal > DigitEnum::ONE ? $awardVal:$orderMoney * $awardVal;
        $award = $award * $orderNumber;
        if($award <= DigitEnum::ZERO){
            return;
        }
        foreach ($userSuperiorAllSid as $value){
            $User = Common::assemble(new UserExample(), $value);
            $awardLimit = $User->integral - $User->venturemoney;
            $award = min($awardLimit, $award);
            $FundsType = FundsEnum::GONGXIANZHIJIANGLI;
            if(UsersModel::editUserMoneyAndVentureInside($conn,$award,$User) != DigitEnum::ONE || Funds::writeFundsIntegral($conn, $User->id, $orderNo, $FundsType, $award, $User->tinymoney + $award, $FundsType) != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED."educationAndrainingExpenses01");
            }
            //激活教培费
            if($awardLimit == $award && $User->level >=1 && $awardLimit > DigitEnum::ZERO){
                $User2 = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
                $award_jh = $User2->tinymoney;
                $FundsType = FundsEnum::EDUCATIONANDTRAININGFEEACTIVATION;
                if(UsersModel::editUserMoneyAndVenturemoneyInside($conn,$award_jh,$User2) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $User2->id, $orderNo, $FundsType, $award_jh, $User2->money + $award_jh, $FundsType) != DigitEnum::ONE || Funds::writeFundsIntegral($conn, $User2->id, $orderNo, $FundsType, -$award_jh, $User2->tinymoney - $award_jh, $FundsType) != DigitEnum::ONE){
                    $conn->shiwuRollback();
                    Result::error(ErrorEnum::PAYMENTFAILED."educationAndrainingExpenses02");
                }
            }
            $agentLimit = self::getAwardVal($conn, Config::STOCK_AGENT);
            if($User->tinymoney >= $agentLimit && $User->partner_reward <= DigitEnum::ZERO && $User->level > DigitEnum::ZERO){
                $User3 = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
                $award_jh = $agentLimit;
                $FundsType = FundsEnum::EDUCATIONANDTRAININGFEEACTIVATION;
                if(UsersModel::editUserMoneyAndVenturemoneyInside($conn,$award_jh,$User3) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $User3->id, $orderNo, $FundsType, $award_jh, $User3->money + $award_jh, $FundsType) != DigitEnum::ONE || Funds::writeFundsIntegral($conn, $User3->id, $orderNo, $FundsType, -$award_jh, $User3->tinymoney - $award_jh, $FundsType) != DigitEnum::ONE){
                    $conn->shiwuRollback();
                    Result::error(ErrorEnum::PAYMENTFAILED."educationAndrainingExpenses03");
                }
            }
            $areaLimit = self::getAwardVal($conn, Config::STOCK_AREA);
            if($User->tinymoney >= $areaLimit && $User->partner_reward <= $agentLimit && $User->level > DigitEnum::ZERO){
                $User4 = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
                $award_jh = $areaLimit - $agentLimit;
                $FundsType = FundsEnum::EDUCATIONANDTRAININGFEEACTIVATION;
                if(UsersModel::editUserMoneyAndVenturemoneyInside($conn,$award_jh,$User4) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $User4->id, $orderNo, $FundsType, $award_jh, $User4->money + $award_jh, $FundsType) != DigitEnum::ONE || Funds::writeFundsIntegral($conn, $User4->id, $orderNo, $FundsType, -$award_jh, $User4->tinymoney - $award_jh, $FundsType) != DigitEnum::ONE){
                    $conn->shiwuRollback();
                    Result::error(ErrorEnum::PAYMENTFAILED."educationAndrainingExpenses04");
                }
            }
            $cityLimit = self::getAwardVal($conn, Config::STOCK_CITY);
            if($User->tinymoney >= $cityLimit && $User->partner_reward <= $areaLimit && $User->level > DigitEnum::ZERO){
                $User5 = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
                $award_jh = $cityLimit - $areaLimit;
                $FundsType = FundsEnum::EDUCATIONANDTRAININGFEEACTIVATION;
                if(UsersModel::editUserMoneyAndVenturemoneyInside($conn,$award_jh,$User5) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $User5->id, $orderNo, $FundsType, $award_jh, $User5->money + $award_jh, $FundsType) != DigitEnum::ONE || Funds::writeFundsIntegral($conn, $User5->id, $orderNo, $FundsType, -$award_jh, $User5->tinymoney - $award_jh, $FundsType) != DigitEnum::ONE){
                    $conn->shiwuRollback();
                    Result::error(ErrorEnum::PAYMENTFAILED."educationAndrainingExpenses05");
                }
            }
        }
    }
    /**
     * 激活教培费
     * */
    public static function activationEducation($conn, $User){
        $User = Common::assemble(new UserExample(), UsersModel::getUserInsideId($conn, $User->id));
        $isSettlement = false;
        if($User->tinymoney > DigitEnum::ZERO){
            $award = $User->tinymoney;
            $upperLimit = self::getUpperLimit($conn, $User);
            $awardLimit = $User->venturemoney + $award;
            if($upperLimit >= $awardLimit){
                $isSettlement = true;
            }else{
                $award = $upperLimit - $User->venturemoney;
                if($award > DigitEnum::ZERO){//&& $Rewardable < $User->tinymoney 就是自信
                    $isSettlement = true;
                }
            }
        }
        if($isSettlement){
            $FundsType = FundsEnum::GONGXIANZHIJIANGLI;
            $orderNo = Utils::createOrderNo();
            if(UsersModel::editUserMoneyThawInside($conn,$award,$User) != DigitEnum::ONE || Funds::writeFundsMoney($conn, $User->id, $orderNo, $FundsType, $award, $User->money + $award, $FundsType) != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED."activationEducation");
            }
        }
    }
    /**
     * 晋级
     * */
    public static function promotion($conn,$User){
        $userSuperiorAllPid = UsersModel::getUserSuperiorAllPid($conn, $User->id);
        foreach ($userSuperiorAllPid as $value){
            $assemble = Common::assemble(new UserExample(), $value);
            if($assemble->level < 4){
                $elevation = self::getElevation($assemble->level);
                if($elevation["direct"] <= UsersModel::getUserActivationCountInsideUid($conn, $assemble->id) && $elevation["team"] <=UsersModel::getUserTeamCountSvipAllInside($conn, $assemble)){
                    $educationLimit = self::getEducationLimit($conn, $assemble->level + 1);
                    if(UsersModel::editUserLevelInside($conn, $educationLimit,$assemble) != DigitEnum::ONE){
                        $conn->shiwuRollback();
                        Result::error(ErrorEnum::PAYMENTFAILED."promotion");
                    }
                }
            }
        }
    }
    /**
     * 业绩更新
     * */
    public static function updatePerformance($conn, $UserExample, $orderMoney){
        if(UsersModel::editUserSachAddInside($conn,$orderMoney,$UserExample) != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::PAYMENTFAILED."updatePerformance");
        }
    }
    /**
     * 教培奖上限查询
     * */
    private static function getUpperLimit($conn,$User){
        $upperLimit = DigitEnum::ZERO;
        $userActivationSum = UsersModel::getUserActivationCountInsideUid($conn, $User->id);
        switch ($User->level){
            case DigitEnum::ZERO :
                if($User->ach > DigitEnum::ZERO || $userActivationSum >= DigitEnum::THREE){
                    $upperLimit = self::getAwardVal($conn,Config::STOCK_ACTIVATION);
                } break;
            case DigitEnum::ONE : $upperLimit = self::getAwardVal($conn,Config::STOCK_AGENT);break;
            case DigitEnum::TWO : $upperLimit = self::getAwardVal($conn,Config::STOCK_AREA);break;
            default : $upperLimit = self::getAwardVal($conn,Config::STOCK_CITY);break;
        }
        return $upperLimit ;
    }
    /**
     * 教培奖上限查询
     * */
    private static function getEducationLimit($conn,$level){
        switch ($level){
            case DigitEnum::ONE : $upperLimit = self::getAwardVal($conn,Config::STOCK_AGENT);break;
            case DigitEnum::TWO : $upperLimit = self::getAwardVal($conn,Config::STOCK_AREA);break;
            default : $upperLimit = self::getAwardVal($conn,Config::STOCK_CITY);break;
        }
        return $upperLimit ;
    }
    /**
     * 管理奖奖励查询
     * */
    private static function getLevelAward($conn,$level){
        switch ($level){
            case DigitEnum::ONE : $awardVal = self::getAwardVal($conn,Config::LEVEL_AGENT);break;
            case DigitEnum::TWO : $awardVal = self::getAwardVal($conn,Config::LEVEL_AREA);break;
            case DigitEnum::THREE : $awardVal = self::getAwardVal($conn,Config::LEVEL_CITY);break;
            case DigitEnum::FOUR : $awardVal = self::getAwardVal($conn,Config::LEVEL_PRO);break;
            default : $awardVal = 0;break;
        }
        return $awardVal;
    }
    /**
     * 晋级条件
     * */
    private static function getElevation($level){
        $Elevation = [];
        switch ($level){
            case DigitEnum::ZERO : $Elevation["direct"] = 3;$Elevation["team"] = 12;break;
            case DigitEnum::ONE :  $Elevation["direct"] = 6;$Elevation["team"] = 72;break;
            case DigitEnum::TWO :  $Elevation["direct"] = 9;$Elevation["team"] = 120;break;
            case DigitEnum::THREE :  $Elevation["direct"] = 12;$Elevation["team"] = 360;break;
        }
        return $Elevation;
    }
    /**
     * 奖励查询
     * */
    private static function getAwardVal($conn,$awardType){
        return ConfigModel::getConfigSingleValName($conn, $awardType);
    }
}
